/************************************************************************************/
/*  Program name CAPFNDEXT_AFR_SETUP.sql                                            */
/*  Creater:  WONG Wing Kin (PCCW - UniHub)                                         */
/*************   History   *************************                                */
/* 30 NOV, 2005   WONG Wing Kin         First created                               */
/************************************************************************************/
ALTER SESSION SET NLS_DATE_FORMAT='YYYYMMDD HH24:MI:SS';
SET SERVEROUTPUT ON SIZE 1000000;
SET VERIFY OFF

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPFNDEXT_AFR_SETUP';

	lv_Scc_Count	NUMBER			:=	0;
	lv_Err_Count	NUMBER			:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	lv_FileName		VARCHAR2(100)	:=	'CAPFND_AFR_SETUP.dat';
	lv_PathName		VARCHAR2(100)	:=	'/tmp';
	lv_UTL_File		UTL_FILE.File_Type;

	lv_NGO			VARCHAR2(100);
	lv_NGO_Count	NUMBER;

	CURSOR Cur_F(p_NGO VARCHAR2) IS
	SELECT
		A.Short_Name,
		B.*
	FROM
		CGL_AFR_SETUP		B,
		GL_SETS_OF_BOOKS	A
	WHERE	UPPER(A.Short_Name)	=	p_NGO
	AND		A.Set_Of_Books_ID	=	B.Set_Of_Books_ID
	ORDER BY
		B.Report_Name;

BEGIN
	lv_NGO			:=	UPPER('&1');

	SELECT	COUNT('A')
	INTO	lv_NGO_Count
	FROM	GL_SETS_OF_BOOKS
	WHERE	UPPER(Short_Name)	=	lv_NGO;

	IF	lv_NGO_Count	>=	1	THEN
		lv_Scc_Count	:=	0;
		lv_Err_Msg		:=	'No Error';
		lv_UTL_File		:=	UTL_FILE.FOpen(lv_PathName, lv_FileName, 'w');
		FOR C1 IN Cur_F(lv_NGO) LOOP
			UTL_FILE.PUT_LINE(
				lv_UTL_File,
				C1.Set_Of_Books_ID||CHR(9)||
				C1.Report_Name||CHR(9)||
				C1.Value_Type||CHR(9)||
				C1.Value1||CHR(9)||
				C1.Value2||CHR(9)||
				C1.Value3||CHR(9)||
				C1.Value4||CHR(9)||
				C1.Value5||CHR(9)||
				C1.Value6||CHR(9)||
				C1.Value7||CHR(9)||
				C1.Value8||CHR(9)||
				C1.Value9||CHR(9)||
				C1.Value10||CHR(9)||
				C1.Value11||CHR(9)||
				C1.Short_Name
			);
			lv_Scc_Count	:=	lv_Scc_Count	+	1;
		END LOOP;
		IF	lv_Scc_Count	=	0	THEN
			lv_Err_Msg	:=	lv_NGO||': No AFR Report for this NGO';
		END IF;
		UTL_FILE.FClose(lv_UTL_File);
		INSERT INTO CAPCNV_LOG(
			PROG_ID,
			PROCESS_DATE,
			RECORD_PROCESSED,
			RECORD_REJECTED,
			RECORD_EXTRACTED,
			ERR_MSG
		) VALUES (
			lv_Prog_ID,
			SYSDATE,
			lv_Scc_Count,
			lv_Err_Count,
			lv_Scc_Count-lv_Err_Count,
			lv_Err_Msg
		);
	ELSE
		lv_Err_Count	:=	lv_Err_Count + 1;
		lv_Err_Msg		:=	lv_NGO||': No such NGO SOB exists';
		INSERT INTO CAPCNV_LOG(
			PROG_ID,
			PROCESS_DATE,
			RECORD_PROCESSED,
			RECORD_REJECTED,
			RECORD_EXTRACTED,
			ERR_MSG
		) VALUES (
			lv_Prog_ID,
			SYSDATE,
			lv_Scc_Count,
			lv_Err_Count,
			lv_Scc_Count-lv_Err_Count,
			lv_Err_Msg
		);
	END IF;

	COMMIT;
END;
/